<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket Demo</title>
    <script>
        let socket;//其他函数要用到socket, 要作为全局变量

        function connect() {
            // 获取用户名输入框的值
            const usernameInput = document.getElementById('usernameInput');
            const username = usernameInput.value.trim();
             // socket = new WebSocket('ws://localhost:8080/ws');
            socket = new WebSocket(`ws://1pp12474nx890.vicp.fun:31610/ws?username=${encodeURIComponent(username)}`);

            socket.onopen = () => {
                console.log('连接已建立');
                // document.getElementById('status').textContent = '已连接';
                document.getElementById('status').textContent = `已连接（用户名：${username}）`;

                // 禁用用户名输入框和连接按钮，避免重复连接
                usernameInput.disabled = true;
                document.querySelector('button[onclick="connect()"]').disabled = true;
            };

            socket.onmessage = (event) => {
                const messages = document.getElementById('messages');
                messages.innerHTML += `<div>${event.data}</div>`;
            };

            socket.onclose = () => {
                document.getElementById('status').textContent = '已断开';
              //  document.getElementById('status').tex
            };
        }

        function sendMessage() {
            const input = document.getElementById('messageInput');
            socket.send(input.value);
            input.value = '';
        }
    </script>
</head>
<body >
<h1>WebSocket Demo</h1>
<input type="text" id="usernameInput" placeholder="请输入用户名"><br>
<button onclick="connect()">连接服务器</button>
<div id="status">未连接</div>

<div>
    <input type="text" id="messageInput" placeholder="输入消息">
    <button onclick="sendMessage()">发送</button>
</div>

<div id="messages"></div>
</body>
</html>